#include "MainLogic.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

mainLogic::mainLogic(){ }

mainLogic::~mainLogic(){ }

void mainLogic::initSensor()
{
	temp.SetTemp(DEFAULT_TEMP);
    current = 50.0;
	cool  = false;
    heat  = false; 
    fanON = false;
    coolON= false;
    heatON= false;
	srand((int)(current));       
}

float mainLogic::GetTemp()
{	
	float target = temp.GetRange();
	int dif = ((target < current) ? (int)(current - target) : (int)(target - current));
	int n = rand();
	
	if((cool == true) && (current > target + RANGE) ){
		coolON = fanON = true;
		if ( current > target )
			current -= (n%13)/10.0;
		else
			current -= (n%dif)/10.0;
	}
	else if((heat == true) && (current < target - RANGE ) ){
		heatON = fanON = true;
		if (current < target )
			current += (n%13)/10.0;
		else
			current += (n%dif)/10.0;
	}
	else{
		if ((n%2) == 0 )
			current += (n%4)/10.0;
		else   // Temp fluctation
			current -= (n%4)/10.0;
		coolON = heatON = false;
	}

	return current; 
}

/**********************
 time structure is 
 HH:MM MM/DD/YYYY
 
***********************/
void mainLogic::GetTime(char output[])
{ 
	t = time(NULL);
	struct tm * l_time;
	
	l_time = localtime(&t);
	sprintf(output,"%4d/%02d/%02d %02d:%02d:05 ", l_time->tm_year + 1900, l_time->tm_mon + 1, l_time->tm_mday, l_time->tm_hour, l_time->tm_min );
        
}

float mainLogic::GetTarget(){	return temp.GetRange();	}

void mainLogic::GetRange(float *t1, float *t2)
{  
	*t1 = temp.GetRangeUpper();
	*t2 = temp.GetRangeLower();	
}

bool mainLogic::SetTemp(float newtemp)
{
	return temp.SetTemp(newtemp);
}

bool mainLogic::heatStatus()
{	return heat;  }

bool mainLogic::coolStatus()
{	return cool;  }

bool mainLogic::heatToggleStatus()
{	(heat ? (heat = false) : (heat = true)); 
	return heat;
}

bool mainLogic::coolToggleStatus()
{	(cool ? (cool = false) : (cool = true));  
	return cool;
}

bool mainLogic::fanStatus()
{	return fanON; }

bool mainLogic::fanToggleStatus()
{ 
	(fanON ? (fanON = false) : (fanON = true));
	return fanON;

}